package com.panfeng.xcloud.boss.provider.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.panfeng.xcloud.boss.provider.member.model.MailMessageInfo;
import com.panfeng.xcloud.boss.provider.member.service.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件service
 *
 * @author xiaobo
 * @version 1.0
 * @since 2019-08-13
 */
@Service
@Slf4j
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailProperties mailProperties;

    /**
     * 发送邮件
     *
     * @param mailMessageInfo
     */
    @Override
    public void sendMail(MailMessageInfo mailMessageInfo) {
        log.info(">>> 开始发送邮箱信息：{} <<<", JSON.toJSONString(mailMessageInfo));
        SimpleMailMessage mimeMessage = new SimpleMailMessage();
        mimeMessage.setFrom(mailProperties.getUsername());
        mimeMessage.setTo(mailMessageInfo.getToAccount());
        mimeMessage.setSubject(mailMessageInfo.getSubject());
        mimeMessage.setText(mailMessageInfo.getContent());
        mailSender.send(mimeMessage);
    }

    /**
     * 发送邮件-待附件
     *
     * @param mailMessageInfo
     * @return
     */
    @Override
    public boolean sendMailAttachment(MailMessageInfo mailMessageInfo) {
        log.info(">>> 开始发送邮箱信息(带附件)：{} <<<", JSON.toJSONString(mailMessageInfo));
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(mailMessageInfo.getToAccount());
            helper.setSubject(mailMessageInfo.getSubject());
            helper.setText(mailMessageInfo.getContent(), true);
            helper.addAttachment(mailMessageInfo.getAttachmentFileName(), mailMessageInfo.getAttachmentFile());
            mailSender.send(mimeMessage);
            return true;
        } catch (MessagingException e) {
            log.error(">>> 发送带附件的邮件异常：{} <<<",e);
            e.printStackTrace();
            return false;
        }
    }
}
